package com.party.admin.biz.area;

import com.party.common.utils.PinyinUtil;
import com.party.core.model.city.Area;
import com.party.core.service.city.IAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * area业务service
 */
@Service
public class AreaBizService {

    @Autowired
    private IAreaService areaService;

    public void addOtherCountries() throws IOException{
        String path = AreaBizService.class.getClassLoader().getResource("").getPath() + "otherArea.sql";
        File file = new File(path);
        InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file), "UTF-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line = null;

        Pattern pattern = Pattern.compile("'(\\d+)', '(.+)', '(\\d+)', '(\\d*)', '(\\d*)'");
        Matcher matcher;

        String code = "";
        String parentCode = "";
        String name = "";

        while ((line = bufferedReader.readLine()) != null) {
            matcher = pattern.matcher(line);
            if (matcher.find()) {
                code = matcher.group(1);
                name = matcher.group(2);
                parentCode = matcher.group(3);
                getSet(code, name, parentCode);
            }
        }
    }

    public Area getSet(String code, String name, String parentCode) {
        Area area = areaService.findByCode(code);
        if (null != area) {
            return area;
        }
        area = new Area();
        area.setParentIds("");
        area.setSort("0");
        area.setName(name);
        area.setCode(code);
        area.setCreateBy("");
        area.setUpdateBy("");

        String pinyin = PinyinUtil.hanziToPinyin(name, "");
        area.setPinyin(pinyin);

        if ("0".equals(parentCode)) {
            area.setParentId("0");
        } else {
            Area parent = areaService.findByCode(parentCode);
            if (null == parent) {
                return null;
            }
            area.setParentId(parent.getId());
        }
        Area max = areaService.findMaxId();

        String maxId = max.getId();
        String id = Integer.valueOf(maxId) + 1 + "";
        area.setId(id);

        areaService.insert(area);
        return area;
    }

}
